package com.stone.serverless.web;

import cn.hutool.core.annotation.AnnotationUtil;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/21 15:24
 * @Version: 1.0.0
 */
public class ServerlessRequestResponseBodyMethodProcessor extends RequestResponseBodyMethodProcessor {
    public ServerlessRequestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> converters) {
        super(converters);
    }

    @SneakyThrows
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        //boolean b = AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) ||
        //        returnType.hasMethodAnnotation(ResponseBody.class);

        Class<?> containingClass = returnType.getContainingClass();
        ClassLoader classLoader = containingClass.getClassLoader();
        Class<? extends Annotation> aClass = (Class<? extends Annotation>) classLoader.loadClass(ResponseBody.class.getName());
        Annotation annotation = AnnotationUtil.getAnnotation(containingClass, aClass);
        if (null != annotation) {
            return true;
        }

        Method method = returnType.getMethod();
        annotation = AnnotationUtil.getAnnotation(method, aClass);
        if (null != annotation) {
            return true;
        }

        return false;
    }

}
